package com.daocao.common.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import com.daocao.common.constants.HttpStatus;
import com.daocao.common.domain.dto.LoginDto;
import com.daocao.common.domain.vo.LoginUserVO;
import com.daocao.common.exception.ServiceException;
import com.daocao.common.service.IAuthService;
import com.daocao.common.utils.JwtUtils;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class AuthServiceImpl implements IAuthService{

    @Autowired
    private JwtUtils jwtUtils;
    
    @Autowired
    private AuthenticationManager authenticationManager;

    //public AuthServiceImpl(AuthenticationManager authenticationManager) {
    //    this.authenticationManager = authenticationManager;
    //}

    /**
     * login方法
     */
    @Override
    public String login(LoginDto loginDto){

        UsernamePasswordAuthenticationToken authentication= 
        new UsernamePasswordAuthenticationToken(loginDto.getAccount(), loginDto.getPassword());
        //调用loaduserbyusername方法
        Authentication authenticate = authenticationManager.authenticate(authentication);
        //获取用户信息，返回的userdetails
        LoginUserVO loginUser = (LoginUserVO)authenticate.getPrincipal();
        //非空抛异常
        if(ObjectUtil.isNull(loginUser)){
            throw new ServiceException(HttpStatus.UNAUTHORIZED,"认证失败");
        }
        //创建Token
        String token = jwtUtils.createToken(loginUser);
        log.info("Token============>{}",token);
        return token;
    }
}
